<template>
  <div class="vehicle-list-container">
    <!-- 搜索和操作区域 -->
    <el-card class="search-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-title">
            <el-icon><Van /></el-icon>
            <span>车辆管理</span>
          </div>
          <div class="header-operations">
            <el-button type="primary" @click="goToAdd" plain>
              <el-icon><Plus /></el-icon>添加车辆
            </el-button>
            <el-button type="danger" @click="handleBatchDelete" :disabled="multipleSelection.length === 0" plain>
              <el-icon><Delete /></el-icon>批量删除
            </el-button>
            <el-button type="success" @click="handleExport" plain>
              <el-icon><Download /></el-icon>导出Excel
            </el-button>
            <el-button type="warning" @click="handleImport" plain>
              <el-icon><Upload /></el-icon>导入Excel
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="illustration-container">
        <img src="https://img.icons8.com/color/96/000000/car--v1.png" alt="Vehicle Illustration" class="illustration-image">
        <div class="illustration-text">
          <h3>车辆管理</h3>
          <p>高效管理小区车辆信息，轻松掌握车辆状态</p>
        </div>
      </div>
      
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="车牌号">
          <el-input v-model="searchForm.licensePlate" placeholder="请输入车牌号" clearable>
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="品牌">
          <el-input v-model="searchForm.brand" placeholder="请输入品牌" clearable>
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="车辆类型">
          <el-select v-model="searchForm.type" placeholder="请选择车辆类型" clearable>
            <el-option label="小型车" value="小型车"></el-option>
            <el-option label="SUV" value="SUV"></el-option>
            <el-option label="中型车" value="中型车"></el-option>
            <el-option label="面包车" value="面包车"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="正常" value="正常"></el-option>
            <el-option label="临时" value="临时"></el-option>
            <el-option label="过期" value="过期"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="search-buttons">
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetForm">重置</el-button>
    </div>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>车辆列表</span>
          <el-tag type="info">共 {{ total }} 条记录</el-tag>
    </div>
      </template>

      <el-table 
        :data="tableData" 
        border 
        style="width: 100%" 
        v-loading="loading"
        @selection-change="handleSelectionChange"
        stripe
        highlight-current-row
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        :empty-text="'暂无车辆数据'"
      >
        <el-table-column type="selection" width="55" fixed="left"></el-table-column>
        <el-table-column prop="id" label="ID" width="80" fixed="left"></el-table-column>
        <el-table-column label="车牌号" width="120">
          <template #default="scope">
            <div class="cell-with-icon">
              <el-icon><Tickets /></el-icon>
              <span>{{ scope.row.licensePlate }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="品牌" width="100">
          <template #default="scope">
            <div class="cell-with-icon">
              <el-icon><Box /></el-icon>
              <span>{{ scope.row.brand }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="型号" width="120">
          <template #default="scope">
            <div class="cell-with-icon">
              <el-icon><Operation /></el-icon>
              <span>{{ scope.row.model }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="颜色" width="100">
          <template #default="scope">
            <el-tag effect="plain">{{ scope.row.color }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="车辆类型" width="100">
          <template #default="scope">
            <el-tag effect="plain">{{ scope.row.type }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="车主" width="120">
          <template #default="scope">
            <div class="cell-with-icon">
              <el-icon><User /></el-icon>
              <span>{{ scope.row.owner?.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="停车位置" width="120">
          <template #default="scope">
            <div class="cell-with-icon">
              <el-icon><Location /></el-icon>
              <span>{{ scope.row.parkingLocation }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="停车证号" width="120">
          <template #default="scope">
            <div class="cell-with-icon">
              <el-icon><Ticket /></el-icon>
              <span>{{ scope.row.parkingPermitNumber }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)" effect="plain">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="200">
          <template #default="scope">
            <div class="cell-with-icon">
              <el-icon><Calendar /></el-icon>
              <span>{{ formatDate(scope.row.createdAt) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button
              size="small"
              @click="handleEdit(scope.row)"
              type="primary"
              text
            >
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button
              size="small"
              @click="handleDelete(scope.row)"
              type="danger"
              text
            >
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-box">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
          background
        />
    </div>
    </el-card>

    <!-- 导入Excel对话框 -->
    <el-dialog v-model="importDialogVisible" title="导入Excel" width="500px">
      <div class="import-dialog-content">
        <el-alert
          title="请先下载模板，按照模板格式填写数据后上传"
          type="info"
          :closable="false"
          style="margin-bottom: 20px;"
        />
        
        <div class="template-download">
          <el-button type="primary" @click="downloadTemplate" size="small">
            <el-icon><Download /></el-icon>下载模板
          </el-button>
        </div>
        
        <el-upload
          class="excel-upload"
          action="#"
          :auto-upload="false"
          :on-change="handleFileChange"
          :file-list="fileList"
          :limit="1"
          accept=".xlsx,.xls"
        >
          <el-button type="primary">选择文件</el-button>
          <template #tip>
            <div class="el-upload__tip">只能上传xlsx/xls文件</div>
          </template>
        </el-upload>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitImport" :loading="importing">
            导入
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  Plus, 
  Edit, 
  Delete, 
  Calendar, 
  Search,
  Van,
  Location,
  Tickets,
  Box,
  Operation,
  User,
  Ticket,
  Download,
  Upload
} from '@element-plus/icons-vue';
import ExcelUtil from '@/utils/ExcelUtil';

export default {
  name: 'VehicleList',
  components: {
    Plus,
    Edit,
    Delete,
    Calendar,
    Search,
    Van,
    Location,
    Tickets,
    Box,
    Operation,
    User,
    Ticket,
    Download,
    Upload
  },
  data() {
    return {
      searchForm: {
        licensePlate: '',
        brand: '',
        type: '',
        status: ''
      },
      tableData: [],
      multipleSelection: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      importDialogVisible: false,
      fileList: [],
      importing: false,
      exportLoading: false
    }
  },
  created() {
    this.fetchData();
  },
  methods: {
    // 获取状态类型
    getStatusType(status) {
      switch(status) {
        case '正常':
          return 'success';
        case '临时':
          return 'warning';
        case '过期':
          return 'danger';
        default:
          return 'info';
      }
    },
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      if (isNaN(date.getTime())) return dateString;
      
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },
    
    // 获取数据
    fetchData() {
      this.loading = true;
      
      // 构建请求参数
      const params = {
        page: this.currentPage - 1,
        size: this.pageSize
      };
      
      // 添加搜索参数
      if (this.searchForm.licensePlate) {
        params.licensePlate = this.searchForm.licensePlate;
      }
      
      if (this.searchForm.brand) {
        params.brand = this.searchForm.brand;
      }
      
      if (this.searchForm.type) {
        params.type = this.searchForm.type;
      }
      
      if (this.searchForm.status) {
        params.status = this.searchForm.status;
      }
      
      // 调用后端API
      axios.get('/api/vehicles', { params })
        .then(response => {
          console.log('车辆列表API响应:', response.data);
          
          // 处理响应数据
          if (response.data && response.data.content) {
            // 分页响应格式
            this.tableData = response.data.content;
            this.total = response.data.totalItems || response.data.totalElements;
          } else if (Array.isArray(response.data)) {
            // 数组响应格式
            this.tableData = response.data;
            this.total = response.data.length;
          } else {
            console.error('未知的响应格式:', response.data);
            this.tableData = [];
            this.total = 0;
          }
          
          // 处理字段不一致的情况
          this.tableData.forEach(item => {
            if (item.plateNumber && !item.licensePlate) {
              item.licensePlate = item.plateNumber;
            }
          });
        })
        .catch(error => {
          console.error('加载车辆列表失败:', error);
          ElMessage.error('加载车辆列表失败');
          this.tableData = [];
          this.total = 0;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    // 搜索
    handleSearch() {
      this.currentPage = 1; // 重置为第一页
      this.fetchData();
    },
    
    // 重置搜索
    resetForm() {
      this.searchForm = {
        licensePlate: '',
        brand: '',
        type: '',
        status: ''
      };
      this.currentPage = 1;
      this.fetchData();
    },
    
    // 前往新增页面
    goToAdd() {
      this.$router.push('/property/personnel/vehicle/add');
    },
    
    // 编辑
    handleEdit(row) {
      this.$router.push({
        path: '/property/personnel/vehicle/add',
        query: { id: row.id }
      });
    },
    
    // 删除单个
    handleDelete(row) {
      ElMessageBox.confirm(
        `确认要删除车牌号为 ${row.licensePlate} 的车辆吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        // 调用API删除车辆
        axios.delete(`/api/vehicles/${row.id}`)
          .then(() => {
            ElMessage.success('删除成功');
            // 重新加载数据
            this.fetchData();
          })
          .catch(error => {
            console.error('删除车辆失败:', error);
            ElMessage.error('删除车辆失败');
          });
      }).catch(() => {
        ElMessage.info('已取消删除');
      });
    },
    
    // 批量删除
    handleBatchDelete() {
      if (this.multipleSelection.length === 0) {
        ElMessage.warning('请至少选择一条记录');
        return;
      }
      
      // 获取所有选中项的ID
      const ids = this.multipleSelection.map(item => item.id);
      
      ElMessageBox.confirm(
        `确认要删除选中的 ${this.multipleSelection.length} 条记录吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        // 调用API批量删除
        axios.delete('/api/vehicles', { data: ids })
          .then(() => {
            ElMessage.success('批量删除成功');
            // 重新加载数据
            this.fetchData();
          })
          .catch(error => {
            console.error('批量删除失败:', error);
            ElMessage.error('批量删除失败');
          });
      }).catch(() => {
        ElMessage.info('已取消删除');
      });
    },
    
    // 选择变更
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    
    // 页码大小变更
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchData();
    },
    
    // 页码变更
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchData();
    },
    
    // 导出Excel
    async handleExport() {
      try {
        this.exportLoading = true;
        
        // 定义表头
        const header = [
          { label: '车牌号', prop: 'licensePlate' },
          { label: '品牌', prop: 'brand' },
          { label: '型号', prop: 'model' },
          { label: '颜色', prop: 'color' },
          { label: '车辆类型', prop: 'type' },
          { label: '车主姓名', prop: 'ownerName' },
          { label: '停车位置', prop: 'parkingLocation' },
          { label: '停车证号', prop: 'parkingPermitNumber' },
          { label: '状态', prop: 'status' }
        ];
        
        // 获取所有数据
        const response = await axios.get('/api/vehicles/all');
        const data = response.data.map(item => {
          // 处理嵌套的车主信息
          if (item.owner && typeof item.owner === 'object') {
            item.ownerName = item.owner.name;
          }
          return item;
        });
        
        // 导出Excel
        ExcelUtil.exportExcel(data, '车辆信息表', header);
        
        ElMessage.success('导出成功');
      } catch (error) {
        console.error('导出失败:', error);
        ElMessage.error('导出失败: ' + (error.message || '未知错误'));
      } finally {
        this.exportLoading = false;
      }
    },
    
    // 打开导入对话框
    handleImport() {
      this.importDialogVisible = true;
      this.fileList = [];
    },
    
    // 下载导入模板
    async downloadTemplate() {
      try {
        // 创建模板数据
        const templateData = [
          {
            licensePlate: '京A12345',
            brand: '丰田',
            model: 'RAV4',
            color: '白色',
            type: '小型车',
            ownerName: '张三',
            parkingLocation: 'A区-123',
            parkingPermitNumber: 'P12345',
            status: '正常'
          }
        ];
        
        // 定义表头
        const header = [
          { label: '车牌号', prop: 'licensePlate' },
          { label: '品牌', prop: 'brand' },
          { label: '型号', prop: 'model' },
          { label: '颜色', prop: 'color' },
          { label: '车辆类型', prop: 'type' },
          { label: '车主姓名', prop: 'ownerName' },
          { label: '停车位置', prop: 'parkingLocation' },
          { label: '停车证号', prop: 'parkingPermitNumber' },
          { label: '状态', prop: 'status' }
        ];
        
        // 导出模板
        ExcelUtil.exportExcel(templateData, '车辆信息导入模板', header);
        
        ElMessage.success('模板下载成功');
      } catch (error) {
        console.error('下载模板失败:', error);
        ElMessage.error('下载模板失败: ' + (error.message || '未知错误'));
      }
    },
    
    // 文件选择变更
    handleFileChange(file) {
      this.fileList = [file];
    },
    
    // 提交导入
    async submitImport() {
      if (!this.fileList.length) {
        ElMessage.warning('请选择要导入的Excel文件');
        return;
      }
      
      try {
        this.importing = true;
        
        // 读取Excel文件
        const file = this.fileList[0].raw;
        
        // 定义表头映射
        const header = [
          { label: '车牌号', prop: 'licensePlate' },
          { label: '品牌', prop: 'brand' },
          { label: '型号', prop: 'model' },
          { label: '颜色', prop: 'color' },
          { label: '车辆类型', prop: 'type' },
          { label: '车主姓名', prop: 'ownerName' },
          { label: '停车位置', prop: 'parkingLocation' },
          { label: '停车证号', prop: 'parkingPermitNumber' },
          { label: '状态', prop: 'status' }
        ];
        
        // 解析Excel数据
        const importedData = await ExcelUtil.importExcel(file, header);
        
        // 提交到后端
        const formData = new FormData();
        formData.append('file', file);
        
        const response = await axios.post('/api/vehicles/import', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        
        ElMessage.success(`导入成功，成功导入${response.data.successCount || importedData.length}条数据`);
        this.importDialogVisible = false;
        this.fetchData(); // 刷新列表
      } catch (error) {
        console.error('导入失败:', error);
        ElMessage.error('导入失败: ' + (error.response?.data?.message || error.message || '未知错误'));
      } finally {
        this.importing = false;
      }
    }
  }
}
</script>

<style scoped>
.vehicle-list-container {
  padding: 20px;
}

/* 搜索卡片样式 */
.search-card {
  margin-bottom: 20px;
}

.search-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
  padding-top: 10px;
  border-top: 1px dashed #ebeef5;
}

.search-buttons .el-button {
  min-width: 120px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
}

.header-title {
  display: flex;
  align-items: center;
}

.header-title .el-icon {
  font-size: 22px;
  margin-right: 8px;
  color: #409EFF;
}

.header-operations {
  display: flex;
  gap: 10px;
}

.header-operations :deep(.el-button) {
  font-size: 16px;
  height: 42px;
  padding: 8px 16px;
}

.header-operations :deep(.el-icon) {
  font-size: 18px;
  margin-right: 5px;
}

/* 插图容器样式 */
.illustration-container {
  display: flex;
  align-items: center;
  background-color: #f0f9ff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
}

.illustration-image {
  width: 80px;
  height: 80px;
  margin-right: 20px;
}

.illustration-text h3 {
  font-size: 20px;
  color: #409EFF;
  margin: 0 0 8px 0;
}

.illustration-text p {
  font-size: 16px;
  color: #606266;
  margin: 0;
}

.search-form {
  display: flex;
  align-items: center;
}

.search-form :deep(.el-form-item__label) {
  font-size: 16px;
}

.search-form :deep(.el-input__inner) {
  font-size: 16px;
  height: 42px;
}

.search-form :deep(.el-select .el-input__inner) {
  font-size: 16px;
  height: 42px;
}

.search-form :deep(.el-button) {
  font-size: 16px;
  height: 42px;
  padding: 10px 20px;
}

/* 表格卡片样式 */
.table-card {
  margin-bottom: 20px;
}

.table-card :deep(.el-table) {
  font-size: 16px;
}

.table-card :deep(.el-table th) {
  font-size: 16px;
  padding: 12px 0;
}

.table-card :deep(.el-table td) {
  padding: 12px 0;
}

.cell-with-icon {
  display: flex;
  align-items: center;
  font-size: 16px;
}

.cell-with-icon .el-icon {
  margin-right: 5px;
  font-size: 18px;
}

.cell-with-icon .el-icon.User {
  color: #67C23A;
}

.cell-with-icon .el-icon.Van {
  color: #409EFF;
}

.cell-with-icon .el-icon.Location {
  color: #E6A23C;
}

.cell-with-icon .el-icon.Calendar {
  color: #909399;
}

/* 分页样式 */
.pagination-box {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.pagination-box :deep(.el-pagination) {
  font-size: 16px;
}

.pagination-box :deep(.el-pagination .el-input__inner) {
  font-size: 16px;
  height: 36px;
}

.pagination-box :deep(.el-pagination button) {
  font-size: 16px;
  min-width: 36px;
  height: 36px;
}

/* 按钮样式调整 */
:deep(.el-button--text) {
  font-size: 16px;
}

:deep(.el-button) {
  font-size: 16px;
}

:deep(.el-tag) {
  font-size: 14px;
  padding: 2px 8px;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 15px;
  }
  
  .illustration-container {
    flex-direction: column;
    text-align: center;
  }
  
  .illustration-image {
    margin-right: 0;
    margin-bottom: 15px;
  }
}

/* 导入导出相关样式 */
.import-dialog-content {
  padding: 10px 0;
}

.template-download {
  margin-bottom: 20px;
  text-align: center;
}

.excel-upload {
  text-align: center;
}

.el-upload__tip {
  margin-top: 10px;
  font-size: 14px;
  color: #909399;
}
</style> 